#include <iostream>
#include <string>
#include <unistd.h>
#include <mysql/mysql.h>

const std::string host = "127.0.0.1";
const std::string user = "root";
const std::string passwd = "";
const std::string db = "conn";
const unsigned int port = 3306;
int main()
{
    //   std::cout << "mysql client version" <<mysql_get_client_info()<<std::endl;
    MYSQL *my = mysql_init(nullptr);
    if (nullptr == my)
    {
        std::cerr << "init MYSQL error" << std::endl;
        return 1;
    }
    if (mysql_real_connect(my, host.c_str(), user.c_str(), passwd.c_str(), db.c_str(), port, nullptr, 0) == nullptr)
    {
        std::cerr << "conect MYSQL error" << std::endl;
        return 2;
    }

    std::string sql = "select * from user";
    int n = mysql_query(my, sql.c_str());
    if (n == 0)
        std::cout << sql << "success" << std::endl;
    else
    {
        std::cerr << sql << "failed" << std::endl;
        return 3;
    }

    MYSQL_RES *res = mysql_store_result(my);
    if (nullptr == res)
    {
        std::cerr << "mysql_store_result error" << std::endl;
        return 4;
    }

    my_ulonglong row = mysql_num_rows(res);
    my_ulonglong fields = mysql_num_fields(res);  

    MYSQL_FIELD* fields_array = mysql_fetch_fields(res);
    for(int i = 0;i < fields;i++)
    {
        std::cout << fields_array[i].name << "\t";
    }
    std::cout<<"\n";

    MYSQL_ROW line;
    for(int i = 0; i<row;i++)
    {
        line = mysql_fetch_row(res);
        for(int j = 0;j < fields;j++)
        {
            std::cout << line[j] <<"\t";
        }
        std::cout<<"\n";
    }

    // std::string sql;
    // while(true)
    // {
    //     std::cout << "MYSQL>>> ";
    //     if(!std::getline(std::cin,sql)||sql == "quit")
    //     {
    //         std::cout<<"bye bye"<<std::endl;
    //         break;
    //     }
    //     int n = mysql_query(my,sql.c_str());
    //     if(n == 0)
    //     {
    //         std::cout<<sql<<"success: "<<n<<std::endl;
    //     }
    //     else{
    //         std::cerr<<sql<<"failed: "<<n<<std::endl;
    //     }

    // }

    // std::cout<<"connect success"<<std::endl;
    mysql_free_result(res);
    mysql_close(my);
    return 0;
}